<?php

namespace app\api\controller\courses;
require_once EXTEND_PATH . 'qrcode/vendor/autoload.php';
use app\common\controller\Api;
use think\Config;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Writer\PngWriter;
use think\Request;
use app\common\model\User as UserModel;

/**
 * 职业课程
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $this->category=model('admin/mechanism/Category');
        $this->courses=model('admin/courses/Courses');
        $this->catalogue=model('admin/courses/Catalogue');
        $this->articlecatalogue=model('admin/courses/Articlecatalogue');
        $this->order=model('admin/courses/Order');
        $this->teacher=model('admin/user/Teacher');
        $this->coursesmoneylog=model('admin/courses/Moneylog');
        $this->zhuanyejieshao=model('admin/mechanism/Zhuanyejieshao');
        $this->usercheck=model('admin/user/Check');
      //  /mechanism/zhuanyejieshao
       // courses/moneylog


    }

    public function teacherInfo($admin_id){


       if($teacherInfo= $this->teacher->get(['admin_id'=>$admin_id])){

           $this->success('OK',$teacherInfo);
       }else{
           $this->error('名师不存在');
       }
    }


    /**
     * 职业课程获得推荐行业
     * @param int $page
     * @param int $limit
     */

    public function zhuanyejieshao(){
        $where['is_commend']=['=','推荐'];
        $where['status']=['=','normal'];

    $mechanism_category_fenleiid= $this->zhuanyejieshao->where($where)->group('mechanism_category_fenleiid')->column('mechanism_category_fenleiid');
        $mechanism_category=$this->category->where('id','in',$mechanism_category_fenleiid)->select();

    foreach ($mechanism_category as $key=>$value){

      $zhuanye_ids=  $this->zhuanyejieshao->where('mechanism_category_fenleiid',$value['id'])->group('mechanism_category_topid')->field('id,user_check_id,image,mechanism_category_fenleiid')->order('weigh desc')->column('mechanism_category_topid');

        $mechanism_category[$key]['zhuanye']=$this->category->where('id','in',$zhuanye_ids)->field('id,name')->select();

       $jibie=$this->zhuanyejieshao->where('mechanism_category_fenleiid',$value['id'])->field('id,user_check_id,image,mechanism_category_topid,mechanism_category_id')->order('weigh desc')->limit('0,8')->select();
     foreach ($jibie as $k=>$v){


         $jibie[$k]['user_check_id']=$this->usercheck->where('id',$v['user_check_id'])->value('name');
              $jibie[$k]['zhuanye']=$this->category->where('id',$v['mechanism_category_topid'])->value('name');
                $jibie[$k]['jibie']=$this->category->where('id',$v['mechanism_category_id'])->value('name');
     }
        $mechanism_category[$key]['jibie']=$jibie;
    }

    $this->success('OK',$mechanism_category);
    }


    /**
     *职业课程某行业下专业下所有的级别
     * @param $mechanism_category_fenleiid
     * @param null $mechanism_category_topid
     * @param int $page
     * @param int $limit
     */
    public function zhuanyejieshaoList($mechanism_category_fenleiid,$mechanism_category_topid=null,$page=1,$limit=10){

        $where['status']=['=','normal'];

        $where['id']=['=',$mechanism_category_fenleiid];
        $mechanism_category=$this->category->where($where)->find();
            $zhuanye_ids=  $this->zhuanyejieshao->where('mechanism_category_fenleiid',$mechanism_category_fenleiid)->group('mechanism_category_topid')->field('id,user_check_id,image')->order('weigh desc')->column('mechanism_category_topid');

            $mechanism_category['zhuanye']=$this->category->where('id','in',$zhuanye_ids)->field('id,name')->select();

            $w['mechanism_category_fenleiid']=['=',$mechanism_category_fenleiid];
              if($mechanism_category_topid!=null){
                  $w['mechanism_category_topid']=['=',$mechanism_category_topid];
              }
            $jibie=$this->zhuanyejieshao->where($w)->field('id,user_check_id,image,mechanism_category_topid,mechanism_category_id')->order('weigh desc')->paginate($limit);;
            foreach ($jibie as $k=>$v){
                $jibie[$k]['user_check_id']=$this->usercheck->where('id',$v['user_check_id'])->value('name');

                $jibie[$k]['zhuanye']=$this->category->where('id',$v['mechanism_category_topid'])->value('name');
                $jibie[$k]['jibie']=$this->category->where('id',$v['mechanism_category_id'])->value('name');

            }
            $mechanism_category['jibie']=$jibie;


        $this->success('OK',$mechanism_category);
    }
    /**
     * 专业详情
     */

    public function zhuanyeDetails($id){

        if($zhuanyejieshaoDetails=$this->zhuanyejieshao->get($id)){
            $zhuanyejieshaoDetails['category']=$this->category->where('id',$zhuanyejieshaoDetails->mechanism_category_fenleiid)->value('name');
            $zhuanyejieshaoDetails['zhuanye']=$this->category->where('id',$zhuanyejieshaoDetails->mechanism_category_topid)->value('name');
            $zhuanyejieshaoDetails['jibie']=$this->category->where('id',$zhuanyejieshaoDetails->mechanism_category_id)->value('name');

            $this->success('OK',$zhuanyejieshaoDetails);
        }else{
            $this->error('专业详情不存在');
        }
    }



    /**
     * 课程分类
     * @param int $pid
     */
   public function category($pid=0){
        $where['pid']=['=',$pid];
       $where['status']=['=','normal'];
        $this->success('OK',$this->category->where($where)->order('weigh desc')->select());
   }

    /**
     * 课程管理
     * @param int $page
     * @param int $limit
     * @param null $pid
     */
   public  function coursesList($page=1,$limit=10,$pid=null,$mechanism_category_top=null,$mechanism_category_two=null,$admin_id=null,$sold_sort=null,$id_sort=null){
       $where=[];
       if($pid!=null){
           $where['c.pid']=['=',$pid];
       }
       if($mechanism_category_top!=null){
           $where['c.mechanism_category_top']=['=',$mechanism_category_top];
       }
      // courses_category_ids
       if($mechanism_category_two!=null){
           $where['c.mechanism_category_two']=['=',$mechanism_category_two];
       }
       if($admin_id!=null){
           $where['c.admin_id']=['=',$admin_id];
       }


       $order = 'c.id desc';

       if ($sold_sort) {
           $order = "c.sales_num $sold_sort";
       }
       if ($id_sort) {
           $order = "c.id $id_sort";
       }


       $coursesList=$this->courses
           ->alias('c')
           ->join('__ADMIN__ a ','c.admin_id= a.id')
           ->field('c.*,a.username')
           ->where($where)
           ->order($order)
           ->paginate($limit);
       $this->success('OK',$coursesList);
   }

    /**
     * 课程详情
     * @param int $id
     */
   public function coursesDetails($id=0){
      if($coursesList=$this->courses->get($id)) {

          $coursesList['recommendCourses']=$this->courses
              ->alias('c')
              ->join('__ADMIN__ a ','c.admin_id= a.id')

              ->field('c.*,a.username')

              ->where('c.id','<>',$id)
              ->where('c.admin_id',$coursesList->admin_id)
              ->order('c.createtime desc')
              ->limit('0,8')
              ->select();

          $this->success('OK',$coursesList);
      }else{
          $this->error('课程不存在');
      }
   }


    /**
     * 视频课程目录
     * @param null $courses_courses_id
     */
   public function catalogue($courses_courses_id=null){
       $where=[];
       if($courses_courses_id!=null){
           $where['courses_courses_id']=['=',$courses_courses_id];
       }
      $catalogue= $this->catalogue->where($where)->order('weigh desc')->field('')->select();
       $this->success('OK',$catalogue);

   }

   /**
    *文章课程目录
    */

    public function articlecatalogue($courses_courses_id=null){
        $where=[];
        if($courses_courses_id!=null){
            $where['courses_courses_id']=['=',$courses_courses_id];
        }
        $catalogue= $this->articlecatalogue->where($where)->order('weigh desc')->field('')->select();
        $this->success('OK',$catalogue);

    }

/**
 * 课程创建订单
 */
    public function CreateOrder($courses_courses_id,$score){
        if($coursesInfo=$this->courses->get($courses_courses_id)) {
         if($this->order->get(['uid'=>$this->auth->id,'courses_courses_id'=>$courses_courses_id,'paystate'=>1])) $this->error('该课程已购买，无需重复购买');
            $order_sn="CS".date('Ymd',time()).rand(10000, 99999);
            $paystate=0;
            $orderstate=1;

            if($score!=0){
                $coursesInfo->price=$coursesInfo->price-$score/Config('site.score_bi');
            }

            if($coursesInfo->price<0){
                $this->error('请正确使用积分');
            }
         if($coursesInfo->price<=0){
             $paystate=1;
             UserModel::score(-$score, $this->auth->id, '支付订单扣除订单号'.$order_sn);
         }


            $data=[
                'order_sn'=>$order_sn,
                'courses_courses_id'=>$courses_courses_id,
                'uid'=>$this->auth->id,
                'admin_id'=>$coursesInfo['admin_id'],
                'saleamount'=>$coursesInfo['price'],
                'payamount'=>$coursesInfo['price'],
                'paytype'=>'',
                'method'=>'',
                'title'=>$coursesInfo['courses_name'],
                'paystate'=>$paystate,
                'orderstate'=>$orderstate,
                'score'=>$score,
                ];

            try{
                db()->startTrans();
                $this->order::Create($data);
                db()->commit();
                $this->success('下单成功',$data);
            }catch (Exception $e){
                db()->rollback();
                $this->error($e->getMessage()?:'下单失败');
            }

        }else{
            $this->error('课程不存在');
        }

    }

    //发起支付
    public function payOrder($order_sn,$paytype,$method=null){
       if($orderInfo=$this->order->get(['order_sn'=>$order_sn])){

           if($orderInfo['paystate']==1){
               $this->error('订单已支付，无需重复支付');
           }
           $params = [
               'amount'=>$orderInfo['payamount'],
               'orderid'=>$orderInfo['order_sn'],
               'type'=>$orderInfo['paytype'],
               'title'=>'购买'.$orderInfo['title'],
               'notifyurl'=>request()->root(true).'/api/Notify/courses_notify?paytype='.$orderInfo['paytype'].'&method='.$method, //回调地址
               'returnurl'=>'',
               'method'=>$method,
               'openid'=>"wx5049d19335c00bd7",

           ];

           $wxret = \addons\epay\library\Service::submitOrder($params);
           if($paytype=='alipay'){
               $r= $this->inviteshopQrcode($wxret['qr_code'],$paytype,$orderInfo['order_sn']);
           }elseif($paytype=='wechat'){
               $r= $this->inviteshopQrcode($wxret['code_url'],$paytype,$orderInfo['order_sn']);
           }

           $this->success('OK',$r);


       }else{
           $this->error('订单已支付');
       }

    }


    public function inviteshopQrcode($qr_code,$paytype,$order_sn)
    {

       $image=$order_sn.'_'.$paytype.'.png';
        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
           // ->data(Request::instance()->domain() . '/manystore?id=' . $uid)
           ->data($qr_code)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->build();

        $result->saveToFile(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        $exist = file_exists(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        if (!$exist) $this->error('获取二维码失败');


      return   cdnurl('/uploads/qrcode/'.$image,true);


    }

    //
    public  function mycoursesList($page=1,$limit=10,$pid=null,$mechanism_category_top=null,$mechanism_category_two=null,$teacher_id=null){
        $where=[];
        if($pid!=null){
            $where['c.pid']=['=',$pid];
        }

        if($mechanism_category_top!=null){
            $where['c.mechanism_category_top']=['=',$mechanism_category_top];
        }

        if($mechanism_category_two!=null){
            $where['c.mechanism_category_two']=['=',$mechanism_category_two];
        }
        if($teacher_id!=null){
            $where['c.admin_id']=['=',$teacher_id];
        }


        $where['paystate']=['=',1];
        $coursesList=$this->courses
            ->alias('c')
            ->join('__ADMIN__ a ','c.admin_id= a.id')
            ->join('__COURSES_ORDER__ co','co.courses_courses_id=c.id')
            ->field('c.*,a.username')
            ->where($where)
            ->order('c.createtime desc')
            ->paginate($limit);
        $this->success('OK',$coursesList);
    }
    public function moneyLog($page=1,$limit=10){
       $teacherInfo= $this->teacher->where('user_id',2)->find();

      // dump($teacherInfo->admin_id);
      $coursesmoneylog=  $this->coursesmoneylog->where('admin_id',$teacherInfo->admin_id)->paginate($limit);
      foreach ($coursesmoneylog as $key=>$value){
          $coursesmoneylog[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
      }

        $this->success('ok',$coursesmoneylog);

    }


    public function recommend(){
       ;
        $this->success('OK', $this->usercheck->where('is_recommend','是')->select());
    }


}
